package com.wffz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wffz.comm.utils.CommUtils;
import com.wffz.mapper.ClientUserMapper;
import com.wffz.mapper.IncomeLogMapper;
import com.wffz.mapper.SignInMapper;
import com.wffz.po.ClientUser;
import com.wffz.po.IncomeLog;
import com.wffz.po.SignIn;
import com.wffz.po.WffzConfig;
import com.wffz.service.SignInService;
import com.wffz.service.WffzConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zgy
 * @className SignInServiceImpl
 * @Description
 * @date 2023-03-15 16:10
 **/
@Service
@Slf4j
public class SignInServiceImpl implements SignInService {

    @Resource
    private SignInMapper signInMapper;

    @Resource
    private WffzConfigService configService;

    @Resource
    private ClientUserMapper mapper;

    @Resource
    private IncomeLogMapper incomeLogMapper;

    @Override
    public List<SignIn> queryUserSignInList(ClientUser clientUser) {
        QueryWrapper<SignIn> wrapper = new QueryWrapper<>();
        List<SignIn> list = signInMapper.selectList(wrapper);
        return list;
    }

    @Override
    public int userSignIn(ClientUser clientUser) {
        SignIn bet = new SignIn();
        bet.setUserId(clientUser.getId());
        bet.setLoginName(clientUser.getLoginName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        bet.setSignInTime(simpleDateFormat.format(date));
        bet.setCreateTime(date);
        int i = signInMapper.insert(bet);

        // 签到加点钱
        String key = "signed_in_amount";
        WffzConfig config = configService.getConfigByKey(key);
        float amount = Float.parseFloat(config.getConfigValue());
        clientUser.setAwayBalance(clientUser.getAwayBalance() == null ? 0f : clientUser.getAwayBalance() + amount);
        mapper.updateById(clientUser);
        // 日志
        IncomeLog incomeLog = new IncomeLog();
        incomeLog.setUserId(clientUser.getId());
        incomeLog.setLoginName(clientUser.getLoginName());
        incomeLog.setAmount(amount);
        incomeLog.setCreateTime(new Date());
        incomeLog.setIncomeType("2");
        incomeLogMapper.insert(incomeLog);
        return i;

    }

    @Override
    public boolean isExitSignIn(ClientUser clientUser) {
        QueryWrapper<SignIn> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", clientUser.getLoginName());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        wrapper.eq("sign_in_time", simpleDateFormat.format(date));
        List<SignIn> list = signInMapper.selectList(wrapper);
        return CommUtils.isNotEmptyList(list);
    }
}
